<?php

namespace app\models;

use app\models\system\SetSms;
use Yii;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use app\util\Util;

/**
 * This is the model class for table "sms".
 *
 * @property int $id
 * @property string $mobile
 * @property string $create_time
 * @property string $update_time
 * @property int $status 0 未使用 1 已使用
 * @property string $expire_at 过期时间
 * @property string $ip
 * @property string $code
 */
class Sms extends \yii\db\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'sms';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['create_time', 'update_time', 'expire_at'], 'safe'],
            [['status'], 'integer'],
            [['mobile', 'ip'], 'string', 'max' => 255],

            [['code'], 'safe'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'mobile' => 'Mobile',
            'create_time' => 'Create Time',
            'update_time' => 'Update Time',
            'status' => 'Status',
            'expire_at' => 'Expire At',
            'ip' => 'Ip',
            'code' => 'Code',
        ];
    }

    public function beforeSave($insert)
    {
        if (parent::beforeSave($insert)) {
            $time = date('Y-m-d H:i:s');
            $this->update_time = $time;
            if ($insert) {
                $this->create_time = $time;
            }
            return true;
        }
        return false;
    }

    /**
     * Generate code
     *
     * @param $mobile
     * @param $code
     * @return bool
     * @throws ClientException
     */
    public static function generateCode($mobile, $code)
    {
        $set = SetSms::getLastOne();
        $timeout = $set->timeout;

        $model = new self();
        $model->mobile = $mobile;
        $model->code = $code;
        $model->expire_at = date('Y-m-d H:i:s', time() + 60 * $timeout);
        $model->status = 0;
        $model->ip = Util::getClientIp();

        /**
         * True to send
         */
        if ($set->switch != 1) {
            self::send($mobile, ['code' => $code]);
        }

        return $model->save();
    }

    /**
     * Verify code
     *
     * @param $mobile
     * @param $code
     * @return bool
     */
    public static function verify($mobile, $code)
    {
        $model = self::find()
            ->where(['mobile' => $mobile, 'status' => 0, 'code' => $code])
            ->one();

        if ($model && strtotime($model->expire_at) >= time()) {

            // define expired time
            $model->expire_at = date('Y-m-d H:i:s', time() - 1);
            $model->status = 1;

            return $model->save();
        }

        return false;
    }

    /**
     * Is send
     *
     * @param $mobile
     * @return bool
     */
    public static function isSend($mobile)
    {
        $sms = self::find()
            ->where(['mobile' => $mobile, 'status' => 0])
            ->orderBy(['id' => SORT_DESC])
            ->one();

        if ($sms && strtotime($sms->expire_at) >= time()) {
            return true;
        }

        return false;
    }

    /**
     * Send
     *
     * @param $mobile
     * @param $code
     * @return bool
     * @throws ClientException
     */
    public static function send($mobile, $code)
    {
        $set = SetSms::getLastOne();

        // Ali keyId, keySecret
        AlibabaCloud::accessKeyClient($set->key_id, $set->key_secret)
            ->regionId('cn-hangzhou')
            ->asDefaultClient();

        try {
            //发送短信
            $result = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                // ->scheme('https') // https | http
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->host('dysmsapi.aliyuncs.com')
                ->options([
                    'query' => [
                        'RegionId' => "cn-hangzhou",
                        'PhoneNumbers' => $mobile,              //发送手机号
                        'SignName' => $set->sign,               //签名
                        'TemplateCode' => $set->template,       //模板ID
                        'TemplateParam' => json_encode($code),  //模板替换变量
                    ],
                ])
                ->request();

            //json转数组
            $result = $result->toArray();

            // 调试用
            // var_dump($result);exit;

            //判断是否发送成功
            if(strtolower($result["Code"]) == "ok" && strtolower($result["Message"]) == "ok"){
                return true;
            }

        } catch (ClientException $e) {
            // echo $e->getErrorMessage() . PHP_EOL;
            // exit;
        } catch (ServerException $e) {
            // echo $e->getErrorMessage() . PHP_EOL;
            // exit;
        }

        return false;
    }
}
